import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
    createPost,
    getPosts,
    getPostDetail,
    updatePost,
    deletePost,
    likePost,
    unlikePost,
    getUserPosts,
    getPostComments,
    addComment,
    deleteComment,
    getCommentReplies
} from '@/api/post'
import { uploadImage } from '@/api/upload'

export const usePostsStore = defineStore('posts', () => {
    const posts = ref([])
    const currentPost = ref(null)
    const loading = ref(false)
    const hasMore = ref(true)
    const page = ref(1)
    const pageSize = ref(10)

    // 获取帖子列表
    const fetchPosts = async (params = {}) => {
        try {
            loading.value = true
            const response = await getPosts({
                page: page.value,
                pageSize: pageSize.value,
                ...params
            })

            if (response.code === 0) {
                if (params.page === 1 || !params.page) {
                    posts.value = response.data.list || response.data
                } else {
                    posts.value = [...posts.value, ...(response.data.list || response.data)]
                }

                // 检查是否还有更多数据
                hasMore.value = response.data.hasMore !== false &&
                    (response.data.list || response.data).length === pageSize.value

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        } finally {
            loading.value = false
        }
    }

    // 加载更多帖子
    const loadMorePosts = async (params = {}) => {
        if (!hasMore.value || loading.value) return

        page.value += 1
        return await fetchPosts(params)
    }

    // 重置分页
    const resetPagination = () => {
        page.value = 1
        hasMore.value = true
        posts.value = []
    }

    // 获取帖子详情
    const fetchPostDetail = async (postId) => {
        try {
            const response = await getPostDetail(postId)
            if (response.code === 0) {
                currentPost.value = response.data
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 创建帖子
    const addPost = async (postData) => {
        try {
            const response = await createPost(postData)
            if (response.code === 0) {
                // 将新帖子添加到列表开头
                posts.value.unshift(response.data)
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 更新帖子 
    const updatePostItem = async (postId, updateData) => {
        try {
            const response = await updatePost(postId, updateData)
            if (response.code === 0) {
                // 更新本地帖子数据
                const index = posts.value.findIndex(post => post.post_id === postId)
                if (index !== -1) {
                    posts.value[index] = { ...posts.value[index], ...updateData }
                }

                if (currentPost.value && currentPost.value.post_id === postId) {
                    currentPost.value = { ...currentPost.value, ...updateData }
                }

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }


    // 删除帖子
    const removePost = async (postId) => {
        try {
            const response = await deletePost(postId)
            if (response.code === 0) {
                // 从本地列表中移除
                posts.value = posts.value.filter(post => post.post_id !== postId)

                if (currentPost.value && currentPost.value.post_id === postId) {
                    currentPost.value = null
                }

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 点赞帖子
    const like = async (postId) => {
        try {
            const response = await likePost(postId)
            if (response.code === 0) {
                updatePostLikeStatus(postId, true)
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 取消点赞
    const unlike = async (postId) => {
        try {
            const response = await unlikePost(postId)
            if (response.code === 0) {
                updatePostLikeStatus(postId, false)
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 更新帖子点赞状态
    const updatePostLikeStatus = (postId, isLiked) => {
        // 更新帖子列表中的点赞状态
        const postIndex = posts.value.findIndex(post => post.post_id === postId)
        if (postIndex !== -1) {
            const post = posts.value[postIndex]
            post.like_count = isLiked ? post.like_count + 1 : Math.max(0, post.like_count - 1)
            post.is_liked = isLiked
        }

        // 更新当前帖子的点赞状态
        if (currentPost.value && currentPost.value.post_id === postId) {
            currentPost.value.like_count = isLiked ? currentPost.value.like_count + 1 : Math.max(0, currentPost.value.like_count - 1)
            currentPost.value.is_liked = isLiked
        }
    }

    // 上传图片
    const uploadPostImage = async (file) => {
        try {
            const formData = new FormData()
            formData.append('file', file)

            const response = await uploadImage(formData)
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 获取用户帖子
    const fetchUserPosts = async (userId) => {
        try {
            const response = await getUserPosts(userId)
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 评论相关方法 
    // 获取帖子评论
    const getPostCommentsAction = async (postId, params = {}) => {
        try {
            const response = await getPostComments(postId, {
                page: params.page || 1,
                pageSize: params.pageSize || 10
            })
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 添加评论（支持回复）
    const addCommentAction = async (commentData) => {
        try {
            const response = await addComment(commentData)
            if (response.code === 0) {
                // 更新帖子的评论数（只有顶级评论才计数）
                if (!commentData.parent_id) {
                    const postIndex = posts.value.findIndex(post => post.post_id === commentData.post_id)
                    if (postIndex !== -1) {
                        posts.value[postIndex].comment_count += 1
                    }

                    // 更新当前帖子的评论数
                    if (currentPost.value && currentPost.value.post_id === commentData.post_id) {
                        currentPost.value.comment_count += 1
                    }
                }

                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 删除评论
    const deleteCommentAction = async (commentId) => {
        try {
            const response = await deleteComment(commentId)
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    // 获取评论的回复
    const getCommentRepliesAction = async (commentId, params = {}) => {
        try {
            const response = await getCommentReplies(commentId, {
                page: params.page || 1,
                pageSize: params.pageSize || 10
            })
            if (response.code === 0) {
                return Promise.resolve(response)
            } else {
                return Promise.reject(new Error(response.msg))
            }
        } catch (error) {
            return Promise.reject(error)
        }
    }

    return {
        posts,
        currentPost,
        loading,
        hasMore,
        page,
        pageSize,
        fetchPosts,
        loadMorePosts,
        resetPagination,
        fetchPostDetail,
        addPost,
        updatePostItem,
        removePost,
        like,
        unlike,
        uploadPostImage,
        fetchUserPosts,
        getPostCommentsAction,
        addCommentAction,
        deleteCommentAction,
        getCommentRepliesAction
    }
})